<template>
    <div class="container text-center">
        <div class="row">
            <div class="col">
                <div class="form-floating">
                    <input type="email" class="form-control" id="uid" placeholder="uid" v-model="uid">
                    <label for="uid">uid</label>
                </div>
            </div>
            <div class="col">
                <div class="form-floating">
                    <input type="email" class="form-control" id="token" placeholder="token" v-model="token">
                    <label for="token">token</label>
                </div>
            </div>
            <div class="col">
                <button type="button" class="btn btn-outline-secondary h-100" @click="query"
                    :disabled="(!uid || uid.length <= 0) && state.query">加载关注用户</button>
            </div>
        </div>
        <div class="row">
            <div class="col">
                <ol class="list-group">
                    <li class="list-group-item list-group-item-action overflow-hidden" v-for="item in items"
                        :key="item.id">
                        <div class="d-flex w-100 justify-content-between">
                            <h5 class="mb-1">{{item.userId}}</h5>
                        </div>
                        <p class="text-start">{{item.nickname}}</p>
                        <p class="text-start">{{`https://${hostname}/homepage/last/${item.userId}`}} <a href="#"
                                class="link-success"
                                @click="openUrlWithNewTab(`https://${hostname}/homepage/last/${item.userId}`)"><i
                                    class="bi bi-box-arrow-right"></i></a></p>
                    </li>
                </ol>
            </div>
        </div>
    </div>
</template>
<script lang="ts" setup>
    import { reactive, ref } from "vue";
    import { sendMessage, localSave, localStorage, cookiesGet } from "@/utils/api"
    import { Reactive, Ref } from "@vue/reactivity";
    import type {ComponentInternalInstance} from "vue"
    const { proxy } = getCurrentInstance() as ComponentInternalInstance;
    const token : Ref<string | undefined> = ref("")
    const uid : Ref<string | undefined> = ref("")
    const hostname : Ref<string> = ref("haijiao.com")
    const items : Reactive<any[]> = reactive([])
    const state = reactive({
        query: false
    })


    const props = defineProps({
        url: {
            type: String,
            default: 'https://haijiao.com',
        },
    })
    onMounted(async () => {
        const localObj = await localStorage().get('user')
        console.log(props.url)
        // 根据url的主机名获取cookies
        if (props.url) {
            hostname.value = new URL(props.url).host
            token.value = (await cookiesGet('token', props.url))?.value
            uid.value = (await cookiesGet('uid', props.url))?.value
            localObj['user'].token = token.value
            localObj['user'].uid = uid.value
            await localSave('user', localObj['user'])
        }
        // cookies中未能获取uid和token,从本地存储中获取
        if (!uid.value && localObj['user']) {
            token.value = localObj['user'].token
            uid.value = localObj['user'].uid
        }
        
        // const localObj = await localStorage().get(uid.value)
        // if (!localObj[uid.value as string]) return
        // items.splice(0, items.length, ...localObj[uid.value as string].follow)
    })
    
    watch(uid, async () => {
        const localObj = await localStorage().get("user")
        if (!localObj['user'] || localObj['user'].follow[uid.value as string].length <= 0) return
        
        items.splice(0, items.length, ...localObj['user'].follow[uid.value as string])
    })
    
    const query = async () => {
        try {
            state.query = true
            const { follow, error } = await sendMessage({ action: 'follow', info: { token: token.value, uid: uid.value } })
            console.log(follow, error)
            if (!follow) {
                proxy?.$toast(`follow: ${error}`)
                return
            }
            // 保存uid,token和follow到user
            const localObj = await localStorage().get("user")
            if (!localObj['user']) {
                localObj['user'] = {token: token.value, uid: uid.value, follow: {}}
            }
            localObj['user'].token = token.value
            localObj['user'].uid = uid.value
            localObj['user'].follow[uid.value as string] = follow
            await localSave('user', localObj['user'])
            
            items.splice(0, items.length, ...follow)
        } finally {
            state.query = false
        }
    }
    const openUrlWithNewTab = async (url : string) => {
        console.log(url)
        const resp = await sendMessage({ action: 'openTabWithUrl', url: url });
        console.log(resp)
    }
</script>